import json
from urllib import parse

import redis
from django.core import serializers, signing
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from utils.redis_pool import POOL
from .models import Collage, Course, Place, Choose
from users.models import BasicUser


# Create your views here.

def get_collageName(request):
    query = Collage.objects.all()
    res_arr = []
    for i in query:
        res_arr.append(i.collage_name)

    res = {
        "status": 200,
        "data": res_arr
    }
    return JsonResponse(res)


def get_courseInfo(request):
    query = Course.objects.all()
    # courses = query.values()
    res_arr = []
    for i in query:
        place_name = Place.objects.filter(id=i.place_id).values()[0]["place_name"]
        teacher_name = BasicUser.objects.filter(user_id=i.teach_user_id).values()[0]["real_name"]
        collage_name = Collage.objects.filter(id=i.collage_id).values()[0]["collage_name"]
        tmp = {
            "course_id": i.id,
            "course_name": i.course_name,
            "teacher_name": teacher_name,
            "collage_name": collage_name,
            "place_name": place_name,
            "max_people": i.max_people,
            "now_people": i.now_people
        }
        res_arr.append(tmp)
    res = {
        "code": 0,
        "data": res_arr
    }
    return JsonResponse(res)


# 根据用户信息拿到课程信息
def get_courseInfoByUser(request):
    token = request.META.get("HTTP_TOKEN")
    user_id = request.GET.get("user_id")
    if token == "" or token is None:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn = redis.Redis(connection_pool=POOL)
    rel_token = conn.get(user_id).decode()
    if rel_token is None or rel_token != token:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn.set(user_id, token, 3600)
    course_id = request.GET.get('course_id')
    course_name = request.GET.get('course_name')
    teacher_name = request.GET.get('teacher_name')
    query_user = BasicUser.objects.filter(user_id=user_id).values()[0]
    collage_id = query_user["collage_id"]
    query = Course.objects.filter(collage_id=collage_id)
    if course_id:
        query = query.filter(id=course_id)
    if course_name:
        query = query.filter(course_name=course_name)
    if teacher_name:
        teacher_name = parse.unquote(teacher_name)
        teacher = BasicUser.objects.filter(real_name=teacher_name)
        if teacher:
            teacher_id = teacher.values()[0]["user_id"]
            query = query.filter(teach_user_id=teacher_id)
    outer = Choose.objects.filter(user_id=user_id)
    res_arr = []
    for i in query:
        is_choice = False
        if outer.filter(course_id=i.id):
            is_choice = True
        place_name = Place.objects.filter(id=i.place_id).values()[0]["place_name"]
        teacher_name = BasicUser.objects.filter(user_id=i.teach_user_id).values()[0]["real_name"]
        collage_name = Collage.objects.filter(id=i.collage_id).values()[0]["collage_name"]
        tmp = {
            "course_id": i.id,
            "course_name": i.course_name,
            "teacher_name": teacher_name,
            "collage_name": collage_name,
            "place_name": place_name,
            "max_people": i.max_people,
            "now_people": i.now_people,
            "is_choice": is_choice
        }
        res_arr.append(tmp)
    limit = request.GET.get('limit', '7')
    paginator = Paginator(res_arr, limit)
    try:
        # GET请求方式，get()获取指定Key值所对应的value值
        # 获取index的值，如果没有，则设置使用默认值1
        num = request.GET.get('page', '1')
        # 获取第几页
        number = paginator.page(num)
    except PageNotAnInteger:
        # 如果输入的页码数不是整数，那么显示第一页数据
        number = paginator.page(1)
    except EmptyPage:
        number = paginator.page(paginator.num_pages)
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
    except Exception:
        return JsonResponse({'msg': '404', 'status': 400})
    res = {
        "code": 0,
        "data": number.object_list,
        "count": paginator.count
    }
    return JsonResponse(res)


def get_choiceCourse(request):
    token = request.META.get("HTTP_TOKEN")
    user_id = request.GET.get("user_id")
    if token == "" or token is None:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn = redis.Redis(connection_pool=POOL)
    rel_token = conn.get(user_id).decode()
    if rel_token is None or rel_token != token:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn.set(user_id, token, 3600)
    course_id = request.GET.get('course_id')
    course_name = request.GET.get('course_name')
    teacher_name = request.GET.get('teacher_name')
    query_user = BasicUser.objects.filter(user_id=user_id).values()[0]
    collage_id = query_user["collage_id"]
    query = Course.objects.filter(collage_id=collage_id)
    if course_id:
        query = query.filter(id=course_id)
    if course_name:
        query = query.filter(course_name=course_name)
    if teacher_name:
        teacher_name = parse.unquote(teacher_name)
        teacher = BasicUser.objects.filter(real_name=teacher_name)
        if teacher:
            teacher_id = teacher.values()[0]["user_id"]
            query = query.filter(teach_user_id=teacher_id)
    outer = Choose.objects.filter(user_id=user_id)
    res_arr = []
    for i in query:
        if outer.filter(course_id=i.id):
            place_name = Place.objects.filter(id=i.place_id).values()[0]["place_name"]
            teacher_name = BasicUser.objects.filter(user_id=i.teach_user_id).values()[0]["real_name"]
            collage_name = Collage.objects.filter(id=i.collage_id).values()[0]["collage_name"]
            tmp = {
                "course_id": i.id,
                "course_name": i.course_name,
                "teacher_name": teacher_name,
                "collage_name": collage_name,
                "place_name": place_name,
                "max_people": i.max_people,
                "now_people": i.now_people,
                "is_choice": True
            }
            res_arr.append(tmp)
    limit = request.GET.get('limit', '7')
    paginator = Paginator(res_arr, limit)
    try:
        # GET请求方式，get()获取指定Key值所对应的value值
        # 获取index的值，如果没有，则设置使用默认值1
        num = request.GET.get('page', '1')
        # 获取第几页
        number = paginator.page(num)
    except PageNotAnInteger:
        # 如果输入的页码数不是整数，那么显示第一页数据
        number = paginator.page(1)
    except EmptyPage:
        number = paginator.page(paginator.num_pages)
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
    except Exception:
        return JsonResponse({'msg': '404', 'status': 400})
    res = {
        "code": 0,
        "data": number.object_list,
        "count": paginator.count
    }
    return JsonResponse(res)


# 用户选课接口
@csrf_exempt
@require_http_methods(['POST'])
def choice_course(request):
    token = request.META.get("HTTP_TOKEN")  # 获取token
    data = json.loads(request.body)  # 获取data

    user_id = data["user_id"]  # 获取用户id
    course_id = data["course_id"]  # 获取用户选课的id
    # 数据校验
    if user_id == "" or user_id is None:
        return JsonResponse({'msg': '系统繁忙', 'status': 400})
    if course_id == "" or course_id is None:
        return JsonResponse({'msg': '系统繁忙', 'status': 400})
    if token == "" or token is None:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    # 连接redis
    conn = redis.Redis(connection_pool=POOL)
    # 拿到真实token
    rel_token = conn.get(user_id).decode()
    # 校验token与真实token
    if rel_token is None or rel_token != token:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    # 续约
    conn.set(user_id, token, 3600)
    try:
        # 创建课程
        course = Course.objects.get(id=course_id)
        if course.now_people == course.max_people:
            return JsonResponse({'msg': '当前课程人数已满', 'status': 400})
        Choose.objects.create(course_id=course_id, user_id=user_id)
        course.now_people += 1
        course.save()
        return JsonResponse({'msg': '选课成功', 'status': 400})
    except Exception:
        return JsonResponse({'msg': '系统繁忙', 'status': 400})


# 取消选课接口
@csrf_exempt
@require_http_methods(['POST'])
def no_choice_course(request):
    token = request.META.get("HTTP_TOKEN")
    data = json.loads(request.body)
    user_id = data["user_id"]
    course_id = data["course_id"]
    if token == "" or token is None:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn = redis.Redis(connection_pool=POOL)
    rel_token = conn.get(user_id).decode()
    if rel_token is None or rel_token != token:
        return JsonResponse({'msg': '登录信息失效', 'status': 400})
    conn.set(user_id, token, 3600)
    try:
        course = Course.objects.get(id=course_id)
        Choose.objects.filter(user_id=user_id, course_id=course_id).delete()
        course.now_people -= 1
        course.save()
        return JsonResponse({'msg': '取消成功', 'status': 400})
    except Exception:
        return JsonResponse({'msg': '系统繁忙', 'status': 400})
